package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

/**
 *	1874
 * 阳泉市人民政府台湾事务办公室	http://www.huaxia.com/mlyq/index.html
 * 滁州市台湾事务办	http://www.huaxia.com/hxcz/index.html
 * @author KK
 *
 */
public class HuaxiaNewsAnalyse implements AnalyseNews {

	private static final String[] regex={
		"http://www.huaxia.com/.*/[0-9]{4}/[0-9]{2}/[0-9]+.html",
	};

	
	public boolean isDetailPage(String url) {
		return RegexUtils.matchAny(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (urlMeta.getHtml() == null) {
		}
		NewsMeta news=new NewsMeta();
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();
		String title=null;
		String content=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);

		doc.select("#rla").remove();

		news.setUrl(url);
		title =doc.select("div.B004").text();
		if (StringUtils.isNullOrEmpty(title)){
			title =doc.select("title").text();
		}

		if(StringUtils.isBlank(title)){
			title=doc.select(".Ftitle").text();
		}
		content=HtmlCleaner.getContentHtml(url,doc.select("td.B005"));
		if(StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url,doc.select("td#oImg"));
			if(StringUtils.isBlank(content)){
				content=HtmlCleaner.getContentHtml(url,doc.select("table.style2"));
			}
		}
		if(StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url,doc.select(".content"));
		}
		date=DateUtils.matchDate(doc.select("div:containsOwn(华夏经纬网)").text());
		if (date==null){
			date=DateUtils.matchDate(doc.select("font[color=#666666]").text());
		}

		if(date == null){
			date=DateUtils.matchDate(doc.select("td[height=26]").text());
		}
		if(date == null){
			date=JSoupUtils.matchDate(doc, "华夏经纬网");
		}
		if(StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url,doc.select("td.Fartic"));
		}
		news.setTitle(StringUtils.trimSpace(title));
		news.setContent(content);
		news.setDate(date);
		news.setType(1);
		return news;
	}

	public static void main(String[] args) {
		HuaxiaNewsAnalyse analyse=new HuaxiaNewsAnalyse();
		String url="http://www.huaxia.com/qh-tw/qhyw/2014/05/3897384.html";
		System.out.println(analyse.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(analyse.parserHtml(meta));
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}
